package com.example.cloud_disk.FileReading;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.Reader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * CSV文件读取服务
 *
 * @author majun
 * @package com.example.cloud_disk.FileReading
 * @date 2024/10/22 21:33
 */

@Service
public class CsvService {

    public Map<String, String> readCsv(MultipartFile csvFile) {
        Map<String, String> studentMap = new HashMap<>();

        try (Reader in = new InputStreamReader(csvFile.getInputStream());
             CSVParser parser = new CSVParser(in, CSVFormat.DEFAULT.withFirstRecordAsHeader())) {

            for (CSVRecord record : parser) {
                String name = record.get("姓名");
                String studentId = record.get("学号");
                if (name != null && studentId != null) {
                    studentMap.put(name, studentId);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return studentMap;
    }
}
